<script setup lang="ts">
  import { onActivated, onDeactivated, ref, watch } from 'vue';
  import {
    getOrderTimeOut,
    getSecondContractRecord,
    secondContractBettingRetry,
  } from '/@/apis/userApi';
  import { useUserId } from '/@/hooks/index';
  import { useRequest } from 'vue-request';
  const imgsmap = JSON.parse(localStorage.getItem('tokensImgsMap') as string);
  // 定义 props
  const props = defineProps<{
    orderId: any;
    currentPrice: { [xx: string]: any };
  }>();
  const { getUserId } = useUserId();
  const userId = getUserId();
  const tradeOrderList = ref<any[]>([]);

  const tradeOrderTimes = ref();
  const emit = defineEmits(['change', 'getBalance']);
  const methodsjGetOrderTimeOut = () => {
    if (orderIds.value.length) {
      requestGetOrderTimeOut.run({ orderIds: orderIds.value.join() });
    }
  };
  // 获取期货外汇列表
  const orderIds = ref<any[]>([]);
  const requestSecondContractRecord = useRequest(getSecondContractRecord, {
    manual: true,
    onSuccess(data: any) {
      orderIds.value = [];
      data.forEach((item: any) => {
        orderIds.value.push(item.id);
        if (item.dirty) {
          const params = {
            contractType: item.buyStatus,
            currentPrice: item.startAmount,
            deliveryAmount: item.amount,
            deliveryTime: item.sid,
            id: item.id,
            member: userId,
            pairsName: item.pairsName,
          };
          requestSecondContractBettingRetry.run(params);
        }
      });
      if (orderIds.value.length && !timer.value) {
        clearInterval(timer.value);
        timer.value = null;
        timer.value = setInterval(methodsjGetOrderTimeOut, 1000);
      }
      tradeOrderList.value = data;
      let arrObj: any = {};
      let pairsNames: any = {};
      tradeOrderList.value.forEach((ele: { [xx: string]: any }) => {
        let index = ele.pairsName + '-' + ele.seconds + ele.secondsTime;
        arrObj[index] = ele;
        pairsNames[ele.pairsName] = ele.pairsName;
      });
      emit('change', arrObj, Object.keys(pairsNames));
      emit('getBalance');
    },
  });
  watch(
    () => props.currentPrice,
    () => {
      tradeOrderList.value.forEach(
        (item: { close: number; pairsName: string; seconds: number; secondsTime: number }) => {
          let index = item.pairsName;
          if (props.currentPrice[index]) {
            item.close = props.currentPrice[index];
          }
          let Tokensindex = item.pairsName.split('/').join('');
          if (props.currentPrice[Tokensindex]) {
            item.close = props.currentPrice[Tokensindex];
          }
        },
      );
    },
    {
      deep: true,
    },
  );
  const timeLength = ref(0);
  const requestGetOrderTimeOut = useRequest(getOrderTimeOut, {
    manual: true,
    onSuccess(data: any) {
      tradeOrderTimes.value = data;
      if (timeLength.value > Object.keys(data).length) {
        requestSecondContractRecord.runAsync({ member: userId, type: 2 });
      }
      timeLength.value = Object.keys(data).length;
      if (timeLength.value === 0) {
        clearInterval(timer.value);
        timer.value = null;
        requestSecondContractRecord.run({ member: userId, type: 2 });
      }
    },
  });
  const requestSecondContractBettingRetry = useRequest(secondContractBettingRetry, {
    manual: true,
    onSuccess(data) {
      // 成功之后掉列表
      if (data) {
        requestSecondContractRecord.run({ member: userId, type: 2 });
      }
    },
    onError() {},
  });
  const timer = ref();
  const times = () => {
    clearInterval(timer.value);
    timer.value = null;
    methodGetOrderTimeOut();
  };
  function methodGetOrderTimeOut() {
    requestSecondContractRecord.run({ member: userId, type: 2 });
  }
  function returnName(name: string) {
    let nameArr = ['CL', 'FCPO', 'GC', 'HG', 'NG', 'OIL', 'XAG', 'XAU', 'XPD', 'XPT'];
    let nameBool = nameArr.some((name1) => {
      return name1 == name;
    });
    if (nameBool) {
      return name + '/USD';
    }
    return name;
  }
  watch(
    () => props.orderId,
    () => {
      times();
    },
  );

  onDeactivated(() => {
    clearInterval(timer.value);
    timer.value = null;
  });
  times();
  onActivated(() => {
    times();
  });
</script>

<template>
  <div class="trade_order">
    <div class="order_list_th">
      <div class="width1">
        <p>{{ $t('Currency') }}</p>
        <p>{{ $t('time') }}</p>
      </div>
      <p class="width2">{{ $t('Amount') }}</p>
      <div class="width3">
        <p>{{ $t('purchasePrice') }}</p>
        <p>{{ $t('Markprice') }}</p>
      </div>
      <p class="width4">{{ $t('Profit') }}</p>
      <p class="width5">{{ $t('Time') }}</p>
    </div>
    <div class="rank_box_list">
      <div v-for="item in tradeOrderList" :key="item.id" class="rank_box_li">
        <div class="width1 flex_center">
          <div class="img_box" v-if="item.flag == 0">
            <div class="flag flag1">
              <img :src="$img(`country/${item.pairsName.split('/')[0]}.png`)" alt="" />
            </div>
            <div class="flag flag2">
              <img :src="$img(`country/${item.pairsName.split('/')[1]}.png`)" alt="" />
            </div>
          </div>
          <div class="img_box" v-else-if="item.flag == 1">
            <div class="flag flag1">
              <img
                :src="`https://s2.coinmarketcap.com/static/img/coins/64x64/${
                  imgsmap[item.pairsName.split('/')[0]]
                }.png`"
                alt=""
              />
            </div>
            <div class="flag flag2">
              <img :src="`https://s2.coinmarketcap.com/static/img/coins/64x64/825.png`" alt="" />
            </div>
          </div>
          <div class="img_box" v-else-if="item.flag == 2">
            <img :src="`/${item.newPairsName}.png`" />
          </div>
          <div>
            <p class="rank_box_text">{{ returnName(item.newPairsName) }}</p>
            <p>{{ item.seconds }}{{ item.secondsTime }}</p>
          </div>
        </div>
        <div class="width2 flex_arrow">
          <div class="arrow" :class="item.buyStatus == 1 ? 'font_green' : 'font_red'">
            <span v-if="item.buyStatus == 1">↑</span>
            <span v-else>↓</span>
          </div>
          <div> {{ item.amount }}</div>
        </div>
        <div class="width3">
          <div>{{ item.startAmount }}</div>
          <div>{{ item.close }}</div>
        </div>
        <div class="width4">
          <span
            v-if="
              (item.startAmount <= item.close && item.buyStatus == 1) ||
              (item.startAmount >= item.close && item.buyStatus == 2)
            "
            class="font_green"
          >
            + {{ parseFloat(((item.amount * item.odds) / 100).toFixed(4)) }}
          </span>
          <span v-else class="font_red">
            - {{ parseFloat(((item.amount * item.odds) / 100).toFixed(4)) }}
          </span>
        </div>
        <div class="width5">
          <span v-if="tradeOrderTimes && tradeOrderTimes[item.id] > 0">{{
            tradeOrderTimes[item.id]
          }}</span>
        </div>
      </div>
    </div>
  </div>
</template>

<style lang="scss" scoped>
  .trade_order {
    background-color: $body;
    .order_list_th {
      @include align-center;
      background: #242424;
      height: 72px;
      font-size: 20px;
      padding: 0 30px;
      color: rgb(102, 102, 102);
    }
    .rank_box_list {
      margin: 0 30px;
    }
    .rank_box_li {
      height: 120px;
      @include align-center;
      border-bottom: 1px solid rgba(255, 255, 255, 0.15);
      font-size: 22px;

      .img_box {
        width: 56px;
        height: 56px;
        background: #242424;
        border-radius: 50%;
        margin-right: 10px;
        position: relative;

        .flag {
          width: 24px;
          height: 24px;
          position: absolute;
        }

        .flag1 {
          top: 12px;
          left: 10px;
        }

        .flag2 {
          top: 20px;
          left: 22px;
        }
      }

      .flex_center {
        display: flex;
        align-items: center;
        flex-wrap: wrap;
        & > div:nth-child(2) {
          flex: 1;
        }
      }
    }

    .width1 {
      width: 28%;
    }

    .width2 {
      width: 20%;
      text-align: center;
    }

    .width3 {
      width: 20%;
      text-align: center;
    }

    .width4 {
      width: 18%;
      text-align: center;
    }

    .width5 {
      width: 14%;
      text-align: right;
    }

    .red {
      color: $primary-red;
      font-weight: bold;
      font-size: 30px;
    }

    .green {
      color: $primary-green;
      font-weight: bold;
      font-size: 30px;
    }
    .flex_arrow {
      @include center;
      .arrow {
        margin-right: 2px;
        font-size: 26px;
      }
    }
    .font-color {
      color: #0063f5;
    }
  }
</style>
